//
//  ALComposeControler.swift
//  ALSinaWeiBoSwift
//
//  Created by 柴瑞军 on 16/4/19.
//  Copyright © 2016年 myCompany. All rights reserved.
//

import UIKit
import SVProgressHUD
class ALComposeControler: UIViewController {

    private var maxOfLength = 25
    // 照片选择view是否显示
    private var isShowPhotoSelectorView = false
    
//    MARK:- 控制器view的生命周期方法
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
     prepareUI()
        
        
        //注册键盘frame变化的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ALComposeControler.beginEditing(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    //当发微博界面显示的时候让键盘弹出
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        // 如果照片选择view没有显示才需要主动弹出键盘
        if !isShowPhotoSelectorView {
            placeholderTextView.becomeFirstResponder()
        }
    }
    //通知监听回调的方法----通知的回调方法也是有系统回掉的,所以当不想将该方法暴露给外界,那么可以用private修饰,如果系统调用就必须加上@objc
    /**
     NSConcreteNotification 0x7fc2560a4220 {name = UIKeyboardWillChangeFrameNotification; userInfo = {
     UIKeyboardAnimationCurveUserInfoKey = 7;
     UIKeyboardAnimationDurationUserInfoKey = "0.25";
     UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
     UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
     UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
     UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
     UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
     UIKeyboardIsLocalUserInfoKey = 1;
     }}
     
     //退出键盘发出的通知
     NSConcreteNotification 0x7fc253d5c550 {name = UIKeyboardWillChangeFrameNotification; userInfo = {
     UIKeyboardAnimationCurveUserInfoKey = 7;
     UIKeyboardAnimationDurationUserInfoKey = "0.25";
     UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
     UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
     UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 796}";
     UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
     UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
     UIKeyboardIsLocalUserInfoKey = 1;
     }}
     
     - parameter notification: <#notification description#>
     */
    @objc private func beginEditing(notification:NSNotification){
    
     //获取键盘的frame
        let keyFrame = notification.userInfo!["UIKeyboardFrameEndUserInfoKey"]!.CGRectValue
        
        //动画时长
        let timeDuration:NSTimeInterval = notification.userInfo!["UIKeyboardAnimationDurationUserInfoKey"]!.doubleValue
        
        let  y = -(UIScreen.mainScreen().bounds.height-keyFrame.origin.y)
        
        self.toolbar.snp_updateConstraints(closure: { (make) in
            make.bottom.equalTo(self.view).offset(y)
        })
        //动画改变toolBar的y方向的约束
        UIView.animateWithDuration(timeDuration) {
            self.toolbar.layoutIfNeeded()
        }
        
    }
    
    
// MARK:- 添加到view上面的子控件
    private func prepareUI(){
        //设置导航条
        setNavgationBar()
        //添加textView
        setTextView()
        //添加图片选择控制器的view
        setPictureSelectorView()
        setToolbar()
        setTipLabel()
    }
    
    private func setPictureSelectorView(){
    
        let photoView = photosSelectorController.view
        photoView.backgroundColor = UIColor.randomColor()
        view.addSubview(photoView)
        // 当一个控制器的view成为另一个控制器的view的子view,那么这个控制器页最好成为另外一个控制器的子控制器
        addChildViewController(photosSelectorController)
        
        //添加约束
        photoView.snp_makeConstraints { (make) in
            make.trailing.leading.equalTo(view)
            make.bottom.equalTo(view).offset(UIScreen.mainScreen().bounds.height * 0.6)
            make.height.equalTo(UIScreen.mainScreen().bounds.height*0.6)
        }
    }
    
    private func setTipLabel(){
    
        view.addSubview(lengthTipLabel)
        
        //设置约束
        lengthTipLabel.snp_makeConstraints { (make) in
            make.trailing.equalTo(toolbar).offset(-5)
            make.bottom.equalTo(toolbar.snp_top).offset(-5)
        }
        
    }
    private func setTextView(){
    
    //添加
       view.addSubview(placeholderTextView)
        //设置约束
        placeholderTextView.snp_makeConstraints { (make) in
            make.edges.equalTo(view)
        }
    }
    
    private func setToolbar(){
        //添加toolBar
        view.addSubview(toolbar)
//        toolbar.backgroundColor = UIColor.greenColor()
        //添加约束
        toolbar.snp_makeConstraints { (make) in
            make.leading.bottom.trailing.equalTo(view)
            make.height.equalTo(44)
        }
        
        //创建一个空的数组
        var items = [UIBarButtonItem]()
        var index = 0
        
        // 每个item对应的图片名称
        let itemSettings = [
            ["imageName": "compose_mentionbutton_background", "action": "mention"],
            ["imageName": "compose_emoticonbutton_background", "action": "emoticon:"],
            ["imageName": "compose_trendbutton_background", "action": "trend"],
            ["imageName": "compose_toolbar_picture", "action": "picture"],
            ["imageName": "compose_add_background", "action": "add"]
        ]

        for dict in itemSettings {
            //每个item对应的图片
            let image = dict["imageName"]
            //每个按钮所触发的方法名
            let action = dict["action"]!
            
            let item = UIBarButtonItem(imageNamed: image!, target: self, action: Selector(action))
            
            items.append(item)
            
            //将创建的对象进行转换
            let button = item.customView as! UIButton
            
            //绑定方法
            button.tag = index
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
            index += 1
        }
        
     //移除最后一个弹簧对象
        items.removeLast()
        
        toolbar.items = items
    }
//MARK:- 导航栏的设置
    private func setNavgationBar(){
    
     navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(ALComposeControler.close))
    navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: #selector(ALComposeControler.send))
        //进来以后先将发送按钮禁用
        navigationItem.rightBarButtonItem?.enabled = false
        
        //添加子view
        setTitleView()
    }
    private func setTitleView(){
        
        let prefixTitle = "发微博"
        
        if let name = ALUserAccountViewModel.userAccountViewModel.userAccount?.screen_name {
            //拼接文字显示的字符串
            let title = prefixTitle + "\n" + name
            
            //创建label
            let label = UILabel()
            label.textAlignment = NSTextAlignment.Center
            label.textColor = UIColor.blackColor()
            label.font = UIFont.systemFontOfSize(ALStatusNameFontSize)
            label.numberOfLines = 0
            //使用属性文本来设置部分文字的颜色
            let attriStringM = NSMutableAttributedString(string: title)
            let range = (title as NSString).rangeOfString(name)
            
            attriStringM.addAttribute(NSForegroundColorAttributeName, value: UIColor.orangeColor(), range: range)
            attriStringM.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(12), range: range)
            
            label.attributedText = attriStringM
            
            label.sizeToFit()
            navigationItem.titleView = label
        }else{
            
            navigationItem.title = prefixTitle
        }
    }
    @objc private func close(){
    
        placeholderTextView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    @objc private func send(){
        // 发布微博
        let text = placeholderTextView.emoticonText()
        // 判断是否超出了长度
        let last = maxOfLength - text.characters.count
        if last < 0 {
            SVProgressHUD.showErrorWithStatus("超出最大长度")
            return
        }
        // 提示正在发微博
        SVProgressHUD.showWithStatus("正在发布微博...")
        //新浪限制发送照片只能发一张,所以图片取出图片选择器中的第一张
        let image = photosSelectorController.photos.first
        
        ALStausAccountViewModel.sharedInstance.sendStatus(text,image: image) { (error) -> () in
            if error != nil {
                ALPrint("发布微博失败: \(error)")
                SVProgressHUD.showErrorWithStatus("发布微博失败")
                return
            }
            
            SVProgressHUD.showSuccessWithStatus("发布微博成功")
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                // 发布微博成功了, 关闭控制器
                self.close()
            })
        }
    }
// MARK: - 按钮点击toolBar上的按钮监听事件
    @objc private func picture() {
        print("图片")
        isShowPhotoSelectorView = true
        // 将照片选择界面动画上来
        photosSelectorController.view.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view)
        }
        
        UIView.animateWithDuration(alDefaultTimeInterval) { () -> Void in
            self.view.layoutIfNeeded()
        }
        
        // 让键盘退下
        placeholderTextView.resignFirstResponder()
    }
    
    @objc private func trend() {
        print("#")
    }
    
    
    @objc private func mention() {
        print("@")
    }
    
    
    @objc private func emoticon(button:UIButton) {
        
//当点击表情按钮的时候不会立马切换键盘,当textView.inputView == nil 的时候使用系统的键盘,当textView.inputView != nil的时候使用自定义键盘
        placeholderTextView.resignFirstResponder()
        //需求:点击按钮后在不同状态下使用不同的背景图片
        //普通状态下的图片
        var normalImage:UIImage?
        //高量状态下的图片
        var highlightedImage : UIImage?
        
        // 之前是系统键盘就换成我们的键盘,之前是我们的键盘就切换到系统键盘
        placeholderTextView.inputView = placeholderTextView.inputView == nil ? emoticonKeyboard : nil
        //判断textView.inputView
        if placeholderTextView.inputView == nil {
            // 系统键盘
            normalImage = UIImage(named: "compose_emoticonbutton_background")
            highlightedImage = UIImage(named: "compose_emoticonbutton_background_highlighted")
        }else{
            // 自定义键盘
            normalImage = UIImage(named: "compose_keyboardbutton_background")
            highlightedImage = UIImage(named: "compose_keyboardbutton_background_highlighted")
        }
        
        button.setImage(normalImage, forState: UIControlState.Normal)
        button.setImage(highlightedImage, forState: UIControlState.Highlighted)
        
        // 等0.25，先让键盘动画下去,在弹出来
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(250 * USEC_PER_SEC)), dispatch_get_main_queue()) { () -> Void in
            self.placeholderTextView.becomeFirstResponder()
        }
        print("表情")
    }
    
    
    @objc private func add() {
        print("加号")
    }

//MARK:- 懒加载
    private lazy var emoticonKeyboard:EmotionkeyBoard = {
    
        let emoticon  = EmotionkeyBoard()
        emoticon.textView = self.placeholderTextView
        
        return emoticon
    }()
    
    //懒加载toolBar
    private lazy var toolbar = UIToolbar()
    //懒加载textView
    private lazy var placeholderTextView :ALPlaceholderTextView = {
        
        let textView = ALPlaceholderTextView()
        // 垂直弹簧效果
        textView.alwaysBounceVertical = true

        // 设置
        textView.font = UIFont.systemFontOfSize(18)
//        textView.text = "我是占位图片..."
        textView.delegate = self
        textView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        return textView
    }()

    //懒加载长度提示label
    private lazy var lengthTipLabel: UILabel = {
    let label = UILabel(fontSize: 14, textColor: UIColor.lightGrayColor())
        
        label.text = String(self.maxOfLength)
        
        label.sizeToFit()
        
        return label
    
    }()
    //懒加载图片添加控制器
    private lazy var photosSelectorController:ALPictureSelectorController = ALPictureSelectorController()
    
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}

//MARK:- UITextView的代理方法
extension ALComposeControler:UITextViewDelegate{

    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        
        
        //监听textView中内容的改变
        //已经输入的内容
        let text = textView.emoticonText()
        
        //计算剩余的长度
        let last = maxOfLength - text.characters.count
        
        //此时重置label的内容
        lengthTipLabel.text = String(last)
        
        //设置label的字体颜色
        let color = last > 0 ? UIColor.lightGrayColor() : UIColor.greenColor()
        
        lengthTipLabel.textColor = color
    }
    
}
